package com.huadao.cart_ccs.experiment.changeLiquidPlan;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseDialogFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.TimeUtil;
import com.huadao.cart_ccs.common.UtilHelpers;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.common.dialog.IDialogResultListener;
import com.huadao.cart_ccs.greendao.GreenDaoManager;
import com.huadao.cart_ccs.greendao.entity.LiquidLoopPlan;
import com.huadao.cart_ccs.greendao.gen.LiquidLoopPlanDao;

import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class LiquidLoopPlanDetailDF extends BaseDialogFragment {
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_plan_type)
    TextView tvPlanType;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.et_fluidpump_speed)
    EditText etFluidpumpSpeed;
    @BindView(R.id.et_waste_speed)
    EditText etWasteSpeed;
    @BindView(R.id.ll_edit)
    LinearLayout ll_edit;
    @BindView(R.id.btn_delete)
    Button btn_delete;
    @BindView(R.id.btn_edit)
    Button btn_edit;
    @BindView(R.id.btn_save)
    Button btn_save;

    private Calendar calendar;
    private LiquidLoopPlanDao liquidLoopPlanDao;
    private LiquidLoopPlan liquidLoopPlan;

    private OnSaveNewPlan onSaveNewPlan;
    public interface OnSaveNewPlan{
        void OnSaveNewPlanSucc(LiquidLoopPlan liquidLoopPlan);
        void OnEditPlanSucc(LiquidLoopPlan liquidLoopPlan);
        void OnDeletePlanSucc(LiquidLoopPlan liquidLoopPlan);
    }

    public static LiquidLoopPlanDetailDF newInstance(LiquidLoopPlan liquidLoopPlan){
        LiquidLoopPlanDetailDF liquidLoopPlanDetailDF=new LiquidLoopPlanDetailDF();
        if(liquidLoopPlan!=null){
            Bundle bundle=new Bundle();
            bundle.putSerializable("LiquidLoopPlan",liquidLoopPlan);
            liquidLoopPlanDetailDF.setArguments(bundle);
        }
        return liquidLoopPlanDetailDF;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialogfrag_add_liquid_loop_plan;
    }

    @Override
    protected void onInit() {
        Bundle bundle=getArguments();
        if(bundle!=null){
            liquidLoopPlan= (LiquidLoopPlan) bundle.get("LiquidLoopPlan");
        }

        if(liquidLoopPlan!=null){
            initValue();
            btn_save.setVisibility(View.GONE);
            ll_edit.setVisibility(View.VISIBLE);
        }else {
            btn_save.setVisibility(View.VISIBLE);
            ll_edit.setVisibility(View.GONE);
        }
        calendar=Calendar.getInstance();
        liquidLoopPlanDao=GreenDaoManager.getInstance().getSession().getLiquidLoopPlanDao();
    }

    private void initValue() {
        tvDate.setText(TimeUtil.date_sdf.format(liquidLoopPlan.getStartTime()));
        tvTime.setText(TimeUtil.time_sdf.format(liquidLoopPlan.getStartTime()));
        etAmount.setText(String.valueOf(liquidLoopPlan.getAmount()));
        etFluidpumpSpeed.setText(String.valueOf(liquidLoopPlan.getFluidIntake_speed()));
        etWasteSpeed.setText(String.valueOf(liquidLoopPlan.getDischard_speed()));
    }

    @Override
    protected boolean isDialog() {
        return  true;
    }

    @OnClick({R.id.tv_date,R.id.tv_time,R.id.btn_save,R.id.btn_delete,R.id.btn_edit})
    public void onViewClicked(View view) {
        int id=view.getId();
        switch (id){
            case R.id.tv_date:
                DialogFragmentHelper.showDateDialog(getFragmentManager(), "", Calendar.getInstance(), new IDialogResultListener<Calendar>() {
                    @Override
                    public void onDataResult(Calendar result) {
                        calendar.set(Calendar.YEAR,result.get(Calendar.YEAR));
                        calendar.set(Calendar.MONTH,result.get(Calendar.MONTH));
                        calendar.set(Calendar.DAY_OF_MONTH,result.get(Calendar.DAY_OF_MONTH));
                        tvDate.setText(TimeUtil.date_sdf.format(calendar.getTime()));
                    }
                },true);
                break;
            case R.id.tv_time:
                DialogFragmentHelper.showTimeDialog(getFragmentManager(), "", Calendar.getInstance(), new IDialogResultListener<Calendar>() {
                    @Override
                    public void onDataResult(Calendar result) {
                        calendar.set(Calendar.HOUR_OF_DAY,result.get(Calendar.HOUR_OF_DAY));
                        calendar.set(Calendar.MINUTE,result.get(Calendar.MINUTE));
                        calendar.set(Calendar.SECOND,0);
                        tvTime.setText(TimeUtil.time_sdf.format(calendar.getTime()));
                    }
                },true);
                break;
            case R.id.btn_save:
                String err=checkParams();
                if(err!=null){
                    showToast(err);
                }else {
                    LiquidLoopPlan liquidLoopPlan=generatePlan();
                    if(onSaveNewPlan!=null){
                        onSaveNewPlan.OnSaveNewPlanSucc(liquidLoopPlan);
                    }
                    this.dismiss();
                }
                break;
            case R.id.btn_delete:
                if(onSaveNewPlan!=null){
                    onSaveNewPlan.OnDeletePlanSucc(liquidLoopPlan);
                }
                this.dismiss();
                break;
            case R.id.btn_edit:
                String errEdit=checkParams();
                if(errEdit!=null){
                    showToast(errEdit);
                }else {
                    LiquidLoopPlan liquidLoopPlan=generatePlan();
                    if(onSaveNewPlan!=null){
                        onSaveNewPlan.OnEditPlanSucc(liquidLoopPlan);
                    }
                    this.dismiss();
                }
                break;
        }
    }

    private String checkParams(){
        String err=null;
        if(TextUtils.isEmpty(tvDate.getText())){
            err="请输入日期";
        }else if(TextUtils.isEmpty(tvTime.getText())){
            err="请输入时间";
        }else if(TextUtils.isEmpty(etAmount.getText())){
            err="请输入体积";
        }else if(TextUtils.isEmpty(etFluidpumpSpeed.getText())){
            err="请输入进液泵速度";
        }else if(TextUtils.isEmpty(etWasteSpeed.getText())){
            err="请输入废液泵速度";
        }else if(TextUtils.isEmpty(tvPlanType.getText())){
            err="请输入计划类型";
        }else {
            LiquidLoopPlan liquidLoopPlan=generatePlan();
            if(isPlanConflict(liquidLoopPlan)){
                err="和已有计划有时间冲突";
            }

        }
        return err;
    }

    public void setOnSaveNewPlan(OnSaveNewPlan onSaveNewPlan) {
        this.onSaveNewPlan = onSaveNewPlan;
    }

    //判断是否和已有计划有冲突
    private boolean isPlanConflict(LiquidLoopPlan liquidLoopPlan){
        List<LiquidLoopPlan> allLiquidLoopPlanList=liquidLoopPlanDao.queryBuilder().where(LiquidLoopPlanDao.Properties.ProjectId.eq(ProjectManager.getInstance().getProjectId())).orderAsc(LiquidLoopPlanDao.Properties.StartTime).list();
        allLiquidLoopPlanList.add(liquidLoopPlan);
        Collections.sort(allLiquidLoopPlanList);
        int index=allLiquidLoopPlanList.indexOf(liquidLoopPlan);
        LiquidLoopPlan prePlan;
        LiquidLoopPlan postPlan;
        if(index==0){
            prePlan=null;
        }else {
            prePlan=allLiquidLoopPlanList.get(index-1);
        }
        if(index==allLiquidLoopPlanList.size()-1){
            postPlan=null;
        }else {
            postPlan=allLiquidLoopPlanList.get(index+1);
        }
        if(prePlan!=null){
            if(getEndTime(prePlan).after(liquidLoopPlan.getStartTime())){
                return true;
            }
        }
        if(postPlan!=null){
            if(postPlan.getStartTime().before(getEndTime(liquidLoopPlan))){
                return true;
            }
        }
        return false;
    }

    //获取计划的持续时间
    private int getDurtionPlan(LiquidLoopPlan liquidLoopPlan){
        double fluidIntakTime=UtilHelpers.calculateTimeBySpeedFlow(liquidLoopPlan.getFluidIntake_speed(),liquidLoopPlan.getAmount());
        double wasteTime=UtilHelpers.calculateTimeBySpeedFlow(liquidLoopPlan.getDischard_speed(),liquidLoopPlan.getAmount());
        return (int) (fluidIntakTime+wasteTime+LiquidLoopPlan.minGapTime);
    }

    //获取计划的结束时间
    private Date getEndTime(LiquidLoopPlan liquidLoopPlan){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(liquidLoopPlan.getStartTime());
        calendar.add(Calendar.SECOND,getDurtionPlan(liquidLoopPlan));
        return calendar.getTime();
    }

    private LiquidLoopPlan generatePlan(){
        int amount= Integer.parseInt(etAmount.getText().toString());
        int fluidPumpSpeed= Integer.parseInt(etFluidpumpSpeed.getText().toString());
        int wastePumpSpeed= Integer.parseInt(etWasteSpeed.getText().toString());

        LiquidLoopPlan liquidLoopPlan=new LiquidLoopPlan();
        liquidLoopPlan.setAmount(amount);
        liquidLoopPlan.setFluidIntake_speed(fluidPumpSpeed);
        liquidLoopPlan.setDischard_speed(wastePumpSpeed);
        liquidLoopPlan.setStartTime(calendar.getTime());

        return liquidLoopPlan;
    }

}
